package test;

public class test2 {
    public static int maxSubArray(int[] nums) {
        int maxSoFar = nums[0]; // 记录到目前为止的最大和
        int currentMax = nums[0]; // 记录当前子数组的最大和

        for (int i = 1; i < nums.length; i++) {
            currentMax = Math.max(nums[i], currentMax + nums[i]); // 更新当前子数组的最大和
            maxSoFar = Math.max(maxSoFar, currentMax); // 更新全局最大和
        }

        return maxSoFar;
    }

    public static void main(String[] args) {
        int[] array1 = {1, -2, 3, 5, -1};
        int[] array2 = {1, -2, 3, -8, 5, 1};
        int[] array3 = {1, -2,3,-2,5,1};

        System.out.println(maxSubArray(array1));
        System.out.println(maxSubArray(array2));
        System.out.println(maxSubArray(array3));
    }
}